<template>
  <div class="container"> 
    <!-- 导航头 -->
    <van-nav-bar
      title="编辑收货地址"
      left-arrow
      @click-left="handleGoBack" 
      fixed
    />
    
    <!-- 表单区域 -->
    <div class="address-form-container">
      <div class="form-wrapper">
        <van-form>
          <!-- 收件人 -->
          <van-field
            v-model="formData.receiverName"
            label="收件人"
            placeholder="请输入收件人姓名"
            required
            class="custom-field"
          />
          
          <!-- 联系方式 -->
          <van-field
            v-model="formData.receiverPhone"
            label="联系方式"
            placeholder="请输入手机号"
            type="tel"
            required
            class="custom-field"
          />
          
          <!-- 行政区域 -->
          <van-field
            v-model="formData.region"
            label="行政区域"
            placeholder="如：北京市 朝阳区"
            required
            class="custom-field"
          />
          
          <!-- 详细地址 -->
          <van-field
            v-model="formData.detailAddress"
            label="详细地址"
            placeholder="如：XX街道XX号"
            required
            class="custom-field"
          />
          
          <!-- 默认地址选项 -->
          <van-checkbox 
            v-model="formData.isDefault" 
            class="default-checkbox"
          >
            设为默认地址
          </van-checkbox>
        </van-form>
      </div>
    </div>

    <!-- 底部按钮 -->
    <van-button 
      class="new-btn"
      round 
      block 
      @click="handleSave"
      :loading="isSubmitting"
    >
      保 存
    </van-button>
    <van-button 
      class="new-btn-1"
      round 
      block 
      @click="handleRemove"
      :loading="isSubmitting"
      type="danger"
    >
      删 除
    </van-button>
  </div> 
</template>

<script setup name="UpdateAddress">
import { ref, reactive, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { showToast } from 'vant';
import { emitter } from '../utils/eventBus';
import { updateAddress, deleteAddress, queryAddresstByid ,setDefaultAddress} from '../api/index';

const router = useRouter();
const route = useRoute();

// 表单数据
const formData = reactive({
  id: null,
  receiverName: '',
  receiverPhone: '',
  region: '',
  detailAddress: '',
  isDefault: 0,
  userId: 1
});

const isSubmitting = ref(false); // 仅保留提交状态


onMounted(async () => {
  const addressId = route.query.id;
  if (!addressId) {
    showToast('地址ID不存在');
    router.back();
    return;
  }

  try {
    const address = await queryAddresstByid(addressId);
    
    if (address) {
      formData.id = address.id;
      formData.receiverName = address.receiverName || '';
      formData.receiverPhone = address.receiverPhone || '';
      formData.region = address.region || '';
      formData.detailAddress = address.detailAddress || '';
      formData.isDefault = address.isDefault || 0;
      formData.userId = address.userId || 1;
    } else {
      showToast('未找到地址信息');
      router.back();
    }
  } catch (error) {
    console.error('获取地址详情失败:', error);
    showToast('获取地址信息失败');
    router.back();
  }
});

// 保存修改
const handleSave = async () => {
  // 表单校验
  if (!formData.receiverName) return showToast('请输入收件人');
  if (!formData.receiverPhone) return showToast('请输入手机号');
  if (!/^1\d{10}$/.test(formData.receiverPhone)) return showToast('手机号格式错误');
  if (!formData.region) return showToast('请输入行政区域');
  if (!formData.detailAddress) return showToast('请输入详细地址');
  if (!formData.id) return showToast('地址信息异常');

  isSubmitting.value = true;
  try {
    const submitData = {
      ...formData,
      isDefault: formData.isDefault ? 1 : 0
    };

    //勾选了“设为默认”
    if (submitData.isDefault === 1) {
      await setDefaultAddress(submitData.id);
    }
    
    await updateAddress(submitData);
    showToast('地址更新成功');
    emitter.emit('updateAddress', submitData);
    
    setTimeout(() => {
      router.push('/address');
    }, 300);
  } catch (error) {
    console.error('更新地址失败：', error);
    showToast('更新失败，请重试');
  } finally {
    isSubmitting.value = false;
  }
};

// 删除地址
const handleRemove = async () => {
  if (!formData.id) return showToast('地址信息异常');
  console.log("aaa",formData.id);

  isSubmitting.value = true;
  try {
    await deleteAddress(formData.id);
    showToast('地址已删除');
    emitter.emit('refreshAddressList');
    
    setTimeout(() => {
      router.push('/address');
    }, 300);
  } catch (error) {
    console.error('删除地址失败：', error);
    showToast('删除失败，请重试');
  } finally {
    isSubmitting.value = false;
  }
};

// 返回上一页
const handleGoBack = () => {
  router.push({name:"address"})
};
</script>

<style scoped>

.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-top: 46px;
  padding-bottom: 80px;
}

.address-form-container {
  padding: 16px;
}

.form-wrapper {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.custom-field {
  --van-field-label-width: 80px;
  --van-field-input-text-align: right;
  margin: 0 0 12px 0 !important;
  border-bottom: 1px solid #f5f5f5;
}

.default-checkbox {
  margin: 10px 0 0 80px;
  color: #666;
}

.new-btn {
  width: 300px;
  margin: 0 auto;
  background-color: #FFD700;
  color: #333;
  font-weight: bold;
  
}
.new-btn-1 {
  width: 300px;
  margin: 0 auto;
  background-color: #ff4d4f;
  color: #fff;
  font-weight: bold;
  margin-top: 8px;
}
</style>